<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search, Plus, Download, Refresh, Edit, Delete } from '@element-plus/icons-vue';
import VehicleDialog from '@/components/VehicleDialog.vue';
import { dataAPI } from '@/http/leancloud';

/**
 * 此页面对应承运管理下的 车辆管理
 */
interface VehicleFromAPI {
  objectId: string;
  vehicleNumber: string;
  vehicleType: string;
  driver: string;
  route: string;
  length: string;
  capacity: string;
  loadVolume: string;
  loadWeight: string;
  status: string | number;
  remark: string;
  createdAt: string;
  updatedAt: string;
  manufactureDate: string;
}

// 查询条件
const queryForm = reactive({
  vehicleNumber: '', // 车牌号
  vehicleType: '', // 车型
  driver: '', // 司机
  route: '', // 绑定路线
  status: '' // 状态
});

// 表格数据
const tableData = ref<any[]>([]);
// 表格加载状态
const loading = ref(false);
// 表格选中的行
const selectedRows = ref<any[]>([]);

// 分页参数
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 车型选项
const vehicleTypeOptions = [
  { value: 'small_truck', label: '小型货车' },
  { value: 'medium_truck', label: '中型货车' },
  { value: 'large_truck', label: '大型货车' },
  { value: 'van', label: '面包车' }
];

// 状态选项
const statusOptions = [
  { value: 1, label: '正常' },
  { value: 2, label: '维修中' },
  { value: 0, label: '停用' }
];

// 字段转换：前端 -> LeanCloud
const convertToLeanCloudData = (data: any) => ({
  plateNo: data.vehicleNumber,
  model: data.vehicleType,
  driver: data.driver, // 只存司机姓名
  route: data.route,
  length: data.length,
  passengerCapacity: data.capacity,
  volumeCapacity: data.loadVolume,
  weightCapacity: data.loadWeight,
  status: data.status,
  remark: data.remark,
  manufactureDate: data.manufactureDate
});

// 获取表格数据
const fetchTableData = async () => {
  loading.value = true;
  try {
    // 不再 include driverId
    const vehicles = await dataAPI.query('Vehicle');
    tableData.value = vehicles.map((vehicle: any) => ({
      id: vehicle.objectId,
      vehicleNumber: vehicle.plateNo,
      vehicleType: vehicle.model,
      driver: vehicle.driver || '', // 只用 driver 字段
      route: vehicle.route,
      length: vehicle.length,
      capacity: vehicle.passengerCapacity,
      loadVolume: vehicle.volumeCapacity,
      loadWeight: vehicle.weightCapacity,
      status: vehicle.status,
      remark: vehicle.remark,
      manufactureDate: vehicle.manufactureDate,
      createTime: vehicle.createdAt ? new Date(vehicle.createdAt).toLocaleString() : '',
      updateTime: vehicle.updatedAt ? new Date(vehicle.updatedAt).toLocaleString() : ''
    }));
    pagination.total = vehicles.length;
  } catch (error) {
    console.error('获取车辆数据失败:', error);
    ElMessage.error('获取数据失败');
  } finally {
    loading.value = false;
  }
};

// 重置查询条件
const resetQueryForm = () => {
  Object.keys(queryForm).forEach(key => {
    (queryForm as any)[key] = '';
  });
  handleSearch();
};

// 查询数据
const handleSearch = () => {
  pagination.currentPage = 1;
  fetchTableData();
};

// 处理表格选择变化
const handleSelectionChange = (rows: any[]) => {
  selectedRows.value = rows;
};

// 处理分页变化
const handlePageChange = (currentPage: number) => {
  pagination.currentPage = currentPage;
  fetchTableData();
};

// 处理每页条数变化
const handleSizeChange = (pageSize: number) => {
  pagination.pageSize = pageSize;
  pagination.currentPage = 1;
  fetchTableData();
};

// 对话框相关状态
const dialogVisible = ref(false);
const isEdit = ref(false);
const currentVehicle = ref<any>(null);

// 新增车辆
const handleAdd = () => {
  isEdit.value = false;
  currentVehicle.value = null;
  dialogVisible.value = true;
};

// 编辑车辆
const handleEdit = (row: any) => {
  isEdit.value = true;
  currentVehicle.value = { ...row };
  dialogVisible.value = true;
};

// 删除车辆
const handleDelete = (row: any) => {
  ElMessageBox.confirm(
    `确定要删除车辆"${row.vehicleNumber}"吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await dataAPI.delete('Vehicle', row.id);
      const index = tableData.value.findIndex(item => item.id === row.id);
      if (index > -1) {
        tableData.value.splice(index, 1);
        pagination.total--;
      }
      ElMessage.success('删除成功');
    } catch (error) {
      console.error('删除车辆失败:', error);
      ElMessage.error('删除失败');
    }
  }).catch(() => {});
};

// 处理对话框确认
const handleDialogConfirm = async (data: any) => {
  try {
    const leancloudData = convertToLeanCloudData(data);
    // 类型转换，确保必填字段类型正确
    leancloudData.length = Number(leancloudData.length);
    leancloudData.passengerCapacity = Number(leancloudData.passengerCapacity);
    leancloudData.volumeCapacity = Number(leancloudData.volumeCapacity);
    leancloudData.weightCapacity = Number(leancloudData.weightCapacity);
    leancloudData.status = Number(leancloudData.status);
    if (!leancloudData.manufactureDate) {
      ElMessage.error('出厂日期不能为空');
      return;
    }
    if (typeof leancloudData.manufactureDate === 'string') {
      leancloudData.manufactureDate = new Date(leancloudData.manufactureDate);
    }
    if (leancloudData.manufactureDate instanceof Date) {
      leancloudData.manufactureDate = {
        __type: 'Date',
        iso: leancloudData.manufactureDate.toISOString()
      };
    }
    console.log('即将保存到LeanCloud的数据', JSON.stringify(leancloudData, null, 2));
    if (isEdit.value) {
      // 编辑模式
      const updateData = { ...leancloudData, objectId: currentVehicle.value.id };
      const result = await dataAPI.save('Vehicle', updateData);
      console.log('编辑保存结果', result);
      if (!result || !result.objectId) {
        ElMessage.error('保存失败，未返回ID');
        return;
      }
      fetchTableData();
    } else {
      // 新增模式
      const result = await dataAPI.save('Vehicle', leancloudData);
      console.log('新增保存结果', result);
      if (!result || !result.objectId) {
        ElMessage.error('保存失败，未返回ID');
        return;
      }
      fetchTableData();
    }
  } catch (error: any) {
    console.error('保存车辆数据失败:', error);
    ElMessage.error('保存失败: ' + (error.message || error));
  }
};

// 导入数据
const handleImport = () => {
  console.log('导入数据');
};

// 导出数据
const exportData = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要导出的记录');
    return;
  }
  console.log('导出数据', selectedRows.value);
};

// 批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的记录');
    return;
  }
  ElMessageBox.confirm(
    `确定要删除选中的${selectedRows.value.length}条记录吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    ElMessage.success('删除成功');
    fetchTableData();
  }).catch(() => {});
};

// 获取车型标签类型
const getVehicleTypeTagType = (type: string) => {
  switch (type) {
    case 'small_truck':
      return 'success';
    case 'medium_truck':
      return 'warning';
    case 'large_truck':
      return 'danger';
    case 'van':
      return 'info';
    default:
      return 'info';
  }
};

// 获取状态标签类型
const getStatusTagType = (status: number) => {
  switch (status) {
    case 1:
      return 'success';
    case 2:
      return 'warning';
    case 0:
      return 'danger';
    default:
      return 'info';
  }
};

// 页面加载时获取数据
onMounted(() => {
  fetchTableData();
});
</script>

<template>
  <div class="vehicle-manage-view">
    <div class="page-header">
      <h2 class="page-title">车辆管理</h2>
    </div>

    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form :model="queryForm" inline>
        <el-form-item label="车牌号">
          <el-input v-model="queryForm.vehicleNumber" placeholder="请输入车牌号" clearable></el-input>
        </el-form-item>

        <el-form-item label="车型">
          <el-select v-model="queryForm.vehicleType" placeholder="请选择" clearable>
            <el-option
              v-for="item in vehicleTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="司机">
          <el-input v-model="queryForm.driver" placeholder="请输入司机姓名" clearable></el-input>
        </el-form-item>

        <el-form-item label="绑定路线">
          <el-input v-model="queryForm.route" placeholder="请输入路线" clearable></el-input>
        </el-form-item>

        <el-form-item label="状态">
          <el-select v-model="queryForm.status" placeholder="请选择" clearable>
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetQueryForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格工具栏 -->
    <div class="table-toolbar">
      <div class="left">
        <el-button type="primary" :icon="Plus" @click="handleAdd">新增</el-button>
        <el-button :icon="Download" @click="handleImport">导入</el-button>
        <el-button type="danger" @click="handleBatchDelete">批量删除</el-button>
      </div>
      <div class="right">
        <el-button :icon="Download" @click="exportData">导出</el-button>
      </div>
    </div>

    <!-- 表格 -->
    <el-table
      v-loading="loading"
      :data="tableData"
      @selection-change="handleSelectionChange"
      style="width: 100%"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="vehicleNumber" label="车牌号" width="120" />
      <el-table-column prop="vehicleType" label="车型" width="120">
        <template #default="{ row }">
          <el-tag :type="getVehicleTypeTagType(row.vehicleType)">
            {{ vehicleTypeOptions.find(item => item.value === row.vehicleType)?.label }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="driver" label="司机" width="100" />
      <el-table-column prop="route" label="绑定路线" width="150" />
      <el-table-column prop="length" label="车长" width="80" />
      <el-table-column prop="capacity" label="核定载客" width="100" />
      <el-table-column prop="loadVolume" label="核载体积" width="120" />
      <el-table-column prop="loadWeight" label="核载重量" width="120" />
      <el-table-column prop="manufactureDate" label="生产日期" width="120">
        <template #default="{ row }">
          {{ row.manufactureDate && row.manufactureDate.iso ? row.manufactureDate.iso.slice(0, 10) : '' }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusTagType(row.status)">
            {{ statusOptions.find(item => item.value == row.status)?.label || `未知状态(${row.status})` }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="150">
        <template #default="{ row }">
          <el-button type="primary" link :icon="Edit" @click="handleEdit(row)">编辑</el-button>
          <el-button type="primary" link>详情</el-button>
          <el-dropdown>
            <el-button type="primary" link>更多</el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="handleDelete(row)">
                  <el-icon><Delete /></el-icon>
                  删除
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div>

    <!-- 车辆对话框 -->
    <VehicleDialog
      v-model:visible="dialogVisible"
      :vehicle-data="currentVehicle"
      :is-edit="isEdit"
      @confirm="handleDialogConfirm"
    />
  </div>
</template>

<style scoped>
.vehicle-manage-view {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-title {
  font-size: 20px;
  font-weight: 500;
  margin: 0;
}

.search-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.table-toolbar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>